package dao.balance;

import util.DButils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class BalanceDaoImpl implements BalanceDao{
    /**
     * 消费
     * @param username
     * @return int
     * @author 夏添
     * @date 2020/11/12 17:26
     */
    public void Out(String username,float out) throws Exception{
        String sql = "select balance from balance where username='"+username+"'";
        Connection con = DButils.getConn();
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery(sql);
        float balance = 0;
        if (rs.next())
            balance = rs.getFloat(1);
        balance -= out;
        sql = "update balance set balance="+balance+" where username='"+username+"'";
        st.executeUpdate(sql);
        DButils.close(rs,st,con);
    }


    /**
     * 收入
     * @param username
     * @author 夏添
     * @date 2020/11/12 17:26
     */
    public void Come(String username,float come) throws Exception{
        String sql = "select balance from balance where username='"+username+"'";
        Connection con = DButils.getConn();
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery(sql);
        float balance = 0;
        if (rs.next())
            balance = rs.getFloat(1);
        balance += come;
        sql = "update balance set balance="+balance+" where username='"+username+"'";
        st.executeUpdate(sql);
        DButils.close(rs,st,con);
    }

    /**
     * 查询余额
     * @param username,come
     * @return float
     * @author 夏添
     * @date 2020/11/12 17:26
     */
    public float getBalance(String username) throws Exception{
        String sql = "select balance from balance where username='"+username+"'";
        Connection con =DButils.getConn();
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery(sql);
        float balance = 0;
        if (rs.next())
            balance = rs.getFloat(1);
        DButils.close(rs,st,con);
        return balance;
    }
}
